<%@ page contentType="text/html;charset=UTF-8"%>
<%@ include file="/common/taglibs.jsp"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<html>
<head>
<title>${data.middleware_id==null?'添加':'修改'}SMSP组件与MQ关联配置5.17.11</title>

	<style type="text/css">
		body{
			background-color: #F8F8F8;
		}
		.form-horizontal .controls span{
			margin-top:0;
		}
		textarea{
			resize:none;
			width:400px;
			height:300px;
		}
		.example{
			line-height: 30px;
		}
		.select2 span{
			display:block !important;
			margin-top: 0px !important;
		}
		.control-group .select2-container {
			width: 216px !important;
		}
		.select2-dropdown {
			width: 220px !important;
		}
		.hover-tip{
			position: relative;
			display: inline-block;
			width:15px;
			height:15px;

		}
		.hover-tip .tips{
			display: none;
			text-align: left;
			color:#FFF;
			position: absolute;
			width:200px;
			padding:10px;
			left:-96px;
			top:21px;
			border-radius:6px;
			background-color: #fe6633;
		}
		.hover-tip:hover .tips{
			display: block;
		}
		.el-select-dropdown .el-select-dropdown__item.selected {
		    color: #13ce66 !important;
		    background-color: #fff !important;
		}
		.pop{
			z-index:999;
			position:fixed;
			top:0;
			left:0;
			width:100%;
			height:100%;
			background-color: rgba(0,0,0,.8);
		}
		.pop .ctx{
			padding:30px;
			background-color: #F4F4F4;
			position: absolute;
			width:700px;
			top:50%;
			left:50%;
			margin-left:-350px;
			transform: translateY(-50%);
		}
		.weight-input{
			width:40px;
		}
	</style>

	<!-- 引入element-ui样式 -->
	<link rel="stylesheet" href="${ctx}/js/element-ui/element-ui.css" />
	<!-- 引入element-ui组件库 -->
	<script src="${ctx}/js/element-ui/vue.min.js"></script>
	<script src="${ctx}/js/element-ui/element-ui.js"></script>
</head>

<body menuId="4021">
	<!--Action boxes-->
	<div class="container-fluid">
		<hr>
		<div class="row-fluid">
			<div class="span12">
				<div class="widget-box">
					<div class="widget-title">
						<span class="icon"> <i class="fa fa-list"></i>
						</span>
						<h5></h5>
					</div>
					<div class="widget-content nopadding" id="app">
						<form class="form-horizontal" method="post" action="#" id="mainForm">
							
							<div class="control-group">
								<label class="control-label">SMSP组件ID</label>
								<div class="controls">
									<u:select id="componentId1" value="${data.componentId}" sqlId="findAllSmspComponent"/>
								</div>
							</div>
							<div class="control-group">
								<label class="control-label">消息类型</label>
								<div class="controls">
									<select name="messageType1" id="messageType">
										<option value="00">DB消息</option>
										<option value="01">移动行业</option>
										<option value="02">移动营销</option>
										<option value="03">联通行业</option>
										<option value="04">联通营销</option>
										<option value="05">电信行业</option>
										<option value="06">电信营销</option>
										<option value="07">行业</option>
										<option value="08">营销</option>
										<option value="11">异常移动行业</option>
										<option value="12">异常移动营销</option>
										<option value="13">异常联通行业</option>
										<option value="14">异常联通营销</option>
										<option value="15">异常电信行业</option>
										<option value="16">异常电信营销</option>
										<%--<option value="20">通道消息</option>--%>
										<option value="21">上行消息</option>
										<option value="22">状态报告缓存</option>
										<option value="23">审核内容请求</option>
										<option value="24">内容审核结果</option>
										<option value="30">smsp_c2s/smsp_http监控消息</option>
										<option value="31">smsp_access监控消息</option>
										<option value="32">smsp_send/smsp_report监控消息</option>
										<option value="33">smsp_reback监控消息</option>
										<option value="34">smsp_charge监控消息</option>
										<option value="35">smsp_audit监控消息</option>
										<option value="36">中间件监控消息</option>
									</select>
								</div>
							</div>
							<div class="control-group">
								<label class="control-label">MQ模式</label>
								<div class="controls">
									<select name="mode1" id="mode">
										<option value="0">生产者</option>
										<option value="1">消费者</option>
									</select>
								</div>
                                <input type="hidden" value="${data.ids}" id="ids" name="ids">
                                <input type="hidden"  id="mode_val" name="mode">
                                <input type="hidden"  id="messageType_val" name="messageType">
                                <input type="hidden"  id="componentId_val" name="componentId">
							</div>
							<input type="hidden" name="mqIdAndOther">
							<div id="channelGroupDiv" class="control-group">
								<div id="quanwang">
									<label class="control-label" id="channelname">{{text}}</label>
									<div class="controls">
										<div v-for="(item, index) in channel" v-if="channel.length > 0">
											<p v-if="modetype">MQ_ID(名称){{item.mq_text}},权重:
												<input type="text" class="weight-input" v-model="item.weight">&nbsp;<span>{{item.percent}}</span>&nbsp;
												<a href="javascript:;" class="btn btn-default" @click="del(index)">删除</a>
											</p>
											<p v-if="!modetype">MQ_ID(名称){{item.mq_text}},拉取速度:
												<input type="text" class="weight-input" v-model="item.speed">&nbsp;&nbsp;
												<a href="javascript:;" class="btn btn-default" @click="del(index)">删除</a>
											</p>
										</div>
										<a href="javascript:;" class="btn btn-success" id="add" @click="open">添加</a>
									</div>
								</div>
							</div>

							<div class="control-group">
								<label class="control-label">描述</label>
								<div class="controls">
									<input name="remark" id="remark" type="text" value="${data.remark}">
								</div>
							</div>
							<div class="control-group">
								<label class="control-label">&nbsp;</label>
								<div class="controls">
									<span id="msg" class="error" style="display: none;"></span>
								</div>
							</div>
							
							<div class="form-actions">
								<%--<input type="hidden" name="id" value="${data.id}">--%>
								<input type="button" onclick="saveMQ(this);" value="保  存" class="btn btn-success">
								<input type="button" value="取 消" class="btn btn-error" onclick="cancel()"/>
							</div>
						</form>
						<div class="pop" style="display: none;">
							<div class="ctx">
								<div id="multipleSelectDiv" class="control-group">
									<div id="mode01" v-if="modetype">
										<label class="control-label">组件生产者</label>
										<div class="controls">
											<el-select v-model="value1" name="producer"   filterable size="large" placeholder="请选择" >
												<el-option
														v-for="item in options"
														:label="item.label"
														:value="item.value"
														:disabled="item.disabled">
												</el-option>
											</el-select>
										</div>
									</div>
									<div id="mode10" v-if="!modetype">
										<label class="control-label">组件消费者</label>
										<div class="controls">
											<el-select v-model="value2" name="consumer"   filterable size="large" placeholder="请选择" >
												<el-option
														v-for="item in options"
														:label="item.label"
														:value="item.value"
														:disabled="item.disabled">
												</el-option>
											</el-select>
										</div>
									</div>
								</div>
									<div id="" class="control-group" v-if="modetype">
										<label class="control-label">输入权重</label>
										<div class="controls">
											<input type="text" v-model="weight" name="weight" >
										</div>
									</div>
									<div id="" class="control-group" v-if="!modetype">
										<label class="control-label">输入拉取速度</label>
										<div class="controls">
											<input type="text" v-model="speed" name="speed" >
										</div>
									</div>
									<div id="" class="control-group">
										<label class="control-label"></label>
										<div class="controls">
											<a href="javascript:;" class="btn btn-success" @click="save">保存</a>
											<a href="javascript:;" class="btn btn-default js-close" @click="close">取消</a>
										</div>
									</div>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>



<script type="text/javascript">
var validate;
var mqIdAndOther = "${data.mqIdAndOther}";
var messageType = "${data.messageType}";
var mode = "${data.mode}";
console.log(mqIdAndOther);
// vue实现多选通道
vm = new Vue({
    el : "#app",
    mounted: function(){
        var that = this;
        this.value1 = '';
        this.value2 = '';
        this.handleChangeFirst();
        $.ajax({
            type : "post",
            async: false,
			data : {
                messageType : $("#messageType").val()
            },
            url : "${ctx}/componentConf5point17point11/mqRelation/queryAllMqQueue",
            success : function(data) {
                //填数据
                var arr = mqIdAndOther.split(",");
                var arr_channel= [];
                for(var i = 0;i < arr.length; i++){
                    if(arr[i] === "" || arr[i] === undefined || arr[i] === null){
                        break;
                    }
                    arr[i] = arr[i].split("|");
                    arr_channel[i] = {};
                    arr_channel[i].val = arr[i][0];
                    arr_channel[i].mq_text = arr[i][2];
                    arr_channel[i].id = arr[i][3];
                    if(that.modetype){
                        arr_channel[i].weight = arr[i][1];
                    }else {
                        arr_channel[i].speed = arr[i][1];
                    }
                    $.extend( arr_channel[i], arr[i][0]);
                }
                that.channel = arr_channel;
                if (data != null) {
                    that.options = data;
                }else{
                    console.log("查询mq队列时出错！");
                }
            }
        });
        that.disableData(); //已经选择的 禁止再选
        //事件绑定
        $("#mode").change(function(){
            $("#ids").val("");
            that.handleChange();

        });
        $("#componentId1").change(function(){
            $("#ids").val("");
            that.getMqInfo();
        });
        $("#messageType").change(function(){
            $("#ids").val("");
            that.getMqInfo();
        });
        $("#mode").change(function(){
            $("#ids").val("");
            that.getMqInfo();
        });

    },
    data : {
        text :"组件生产者",
        options : [],
        value: '',
        weight:'',
        speed:'',
        channel : [],
		value1:'',
		value2:'',
        modetype: true,
		MQ_text:''
    },
    watch : {
        channel : {
            handler: function (val, oldVal){
                var total = 0;

				if(this.modetype){
                    for(var i =0; i < val.length; i++){
                        if(!/^[0-9]+?$/.test(val[i].weight)){
                            layer.msg("权重格式错误",{icon:2})
                            return;
                        }
                        if(val[i].weight){
                            total += val[i].weight*1;
                        }

                    }
                    for(var i =0; i < val.length; i++){
                        if(total==0){
                            val[i].percent=(0).toFixed(2)+"%";
						}else {
                            val[i].percent = ((val[i].weight / total) * 100).toFixed(2) + "%";
						}

                    }
                }else {
                    for(var i =0; i < val.length; i++){
                        if(!/^[0-9]+?$/.test(val[i].speed)){
                            layer.msg("拉取速度格式错误",{icon:2})
                            return;
                        }
                        if(val[i].speed){
                            total += val[i].speed*1;
                        }

                    }
                    for(var i =0; i < val.length; i++){
                        val[i].percent = ((val[i].speed / total) * 100).toFixed(2) + "%";
                    }
                }
            },
            deep: true,
        },
        value1 : function(value){
            this.$nextTick(function(){
//                $("input[name='producer']").val(value);
				this.value = value;
                this.MQ_text = $("input[name='producer']").val()
                console.log("watch value1 :" + $("input[name='producer']").val());
            })
        },
        value2 : function(value){
            this.$nextTick(function(){
//                $("input[name='consumer']").val(value);
                this.value = value;
                this.MQ_text = $("input[name='consumer']").val()
                console.log("watch value2 :" + $("input[name='consumer']").val());
            })
        }
    },
    methods : {
        disableData : function(){
			var option = this.options;
            var checked = this.channel;
            for(var i = 0; i < option.length; i++){
                var now_option = option[i];
                for(var j = 0; j < checked.length; j++){
                    if(now_option.value == checked[j].val){
                        now_option.disabled = true;
                    }
                }
            }
        },
        ableData : function(index){
            var option = this.options;
            var checked = this.channel;
            //已选择的禁用
            for(var i = 0; i < option.length; i++){
                var now_option = option[i];

                if(now_option.value == checked[index].val){
                    now_option.disabled = false;
                    this.channel.splice(index,1);
                    break;
                }

            }
        },
        handleChange : function(val){
            var value ;
			value = $("#mode").val()
            if(value == 0){
                this.text = "组件生产者";
				this.modetype = true;
            }else if(value == 1){
                this.text = "组件消费者";
                this.modetype = false;
            }
        },
        handleChangeFirst : function(val){
            var value ;
            if(mode){
                value= mode;
            }else {
                value = $("#mode").val()
            }
            if(value == 0){
                this.text = "组件生产者";
                this.modetype = true;
            }else if(value == 1){
                this.text = "组件消费者";
                this.modetype = false;
            }
        },
        close : function(){
            $(".pop").hide();
            this.weight = "";
            this.speed = "";
            this.value1 = "";
            this.value2 = "";
        },
        open : function(){
            $(".pop").show();
            var that = this;
            $.ajax({
                type : "post",
                async: false,
                data : {
                    messageType : $("#messageType").val()
                },
                url : "${ctx}/componentConf5point17point11/mqRelation/queryAllMqQueue",
                success : function(data) {
                    if (data != null) {
                        that.options = data;
                    }else{
                        console.log("查询mq队列时出错！");
                    }
                }
            });
            that.disableData();
        },
        getMqInfo : function () {
            var that = this;
            $.ajax({
                type : "post",
                async: false,
                data : {
                    componentId : $("#componentId1").val(),
                    mode : $("#mode").val(),
                    messageType : $("#messageType").val()
                },
                url : "${ctx}/componentConf5point17point11/mqRelation/searchByCMM",
                success : function(data) {
                    //填数据
					if(data.ids){
					    $("#ids").val(data.ids);
                    }
                    if(data.mqIdAndOther){
                        var arr = data.mqIdAndOther.split(",");
                        var arr_channel= [];
                        for(var i = 0;i < arr.length; i++){
                            if(arr[i] === "" || arr[i] === undefined || arr[i] === null){
                                break;
                            }
                            arr[i] = arr[i].split("|");
                            arr_channel[i] = {};
                            arr_channel[i].val = arr[i][0];
                            arr_channel[i].mq_text = arr[i][2];
                            arr_channel[i].id = arr[i][3];
                            if(that.modetype){
                                arr_channel[i].weight = arr[i][1];
                            }else {
                                arr_channel[i].speed = arr[i][1];
                            }
                            $.extend( arr_channel[i], arr[i][0]);
                        }
                        that.channel = arr_channel;
                    }else {
                        that.channel = [];
                    }

                }
            });
        },
        //保存通道
        save : function(){
            var o = {
                val : this.value,
                weight : this.weight,
                speed : this.speed,
                percent : "",
				mq_text : this.MQ_text
            }
            if(this.modetype){
                if(!/^[0-9]+?$/.test(o.weight)){
                    layer.msg("权重只能整数且不能为空",{icon:2})
                    return;
                }
                if(!this.value){
                    layer.msg("组件生产者不能为空",{icon:2})
                    return;
                }
            }else {
                if(!/^[0-9]+?$/.test(o.speed)){
                    layer.msg("拉取速度只能整数且不能为空",{icon:2})
                    return;
                }
                if(!this.value){
                    layer.msg("组件消费者不能为空",{icon:2})
                    return;
                }
            }


            this.channel = (this.channel).concat(o);
            console.log(this.channel);
            this.weight = "";
            this.speed = "";
            this.value1 = "";
            this.value2 = "";
            $(".pop").hide();
            this.disableData();
        },
        del : function(i){
            var that = this;
            var arr = [];
            if(this.modetype){
				var weight = this.channel[i].weight;
				var id = this.channel[i].id || -1;
				arr[i] = this.channel[i].val + "|" + weight + "|" +id;
                $("input[name='mqIdAndOther']").val(arr[i]);
            }else {
				var getRate = this.channel[i].speed;
				var id = this.channel[i].id || -1;
				arr[i] = this.channel[i].val + "|" + getRate  + "|" +id;
                $("input[name='mqIdAndOther']").val(arr[i]);
            }
            layer.confirm('确定删除吗？', {
                btn: ['确定','取消'], //按钮
                area:['300px','auto'],
                title:"删除提示"
            }, function(){
                $.ajax({
                    type : "post",
                    data : {
                        id : id
                    },
                    url : "${ctx}/componentConf5point17point11/mqRelation/singleDelete",
                    success : function(data) {
                        //填数据
                        if(data.result == 'success'){
                            layer.msg(data.msg)
                            that.channel.splice(i,1);
                            that.disableData();
                        }else {
                            layer.msg(data.msg)
                        }
                    }
                });
            });
        }
    }
});



$(function(){
    if(mode){
        $("#mode").attr('disabled','true');
        $("#messageType").attr('disabled','true');
        $("#componentId1").attr('disabled','true');
        $("#mode").val(mode);
        $("#messageType").val(messageType);
    }
    $("#mode_val").val($("#mode").val());
    $("#messageType_val").val($("#messageType").val());
    $("#componentId_val").val($("#componentId1").val());
	$.validator.defaults.ignore = "";
	//表单验证规则
	validate = $("#mainForm").validate({
		rules: {
			componentId1:{
				required:true
			},
			messageType:{
				required:true
			},
			producer:{
				checkProducerAndConsumer: true
			},
			consumer:{
				checkProducerAndConsumer: true
			}
		},
		messages: {
			componentId1 : '请选择组件ID',
			messageType : '请选择消息类型'
		}
	});
	
	
	jQuery.validator.addMethod("checkProducerAndConsumer",
			function(value, element) {
				var producer = $("input[name='producer']").val()
				var consumer = $("input[name='consumer']").val()
				if($.trim(producer) == '' && $.trim(consumer) == ''){
					return false;
				}else{
					return true;
				}
				return this.optional(element) || (reg.test(value));
			}, "消费者和生产者不能均为空");
});


function cancel() {
    parent.window.location.reload();
}

function saveMQ(btn){
	$("#msg").hide();
    $("#mode_val").val($("#mode").val());
    $("#messageType_val").val($("#messageType").val());
    $("#componentId_val").val($("#componentId1").val());
	if(!validate.form()){
		return;
	}
    var channel = vm.channel;
	var modetype = vm.modetype;

    if(channel=="" ||channel==undefined){
        if(modetype){
            layer.msg("请选择对应组件及配置权重！",{icon:2})
        }else {
            layer.msg("请选择对应组件及配置拉取速度！",{icon:2})
        }
        return;
    }
    var arr = [], total = 0;
    if(modetype){
        var weightTotal = 0;
        for(var i = 0; i < channel.length; i++){
            var weight = channel[i].weight;
            var id = channel[i].id || -1;
            weightTotal += channel[i].weight;
            if(!/^[0-9]+?$/.test(weight)){
                layer.msg("权重只能整数且不能为空",{icon:2});
                return;
            }
            if(weight > 100){
                layer.msg("单个组件权重不能大于100",{icon:2});
                return;
            }

            arr[i] = channel[i].val + "|" + weight + "|" +id;
            total += Number(weight);
        }
        if(weightTotal <= 0){
            layer.msg("总权重必须大于0",{icon:2});
            return;
        }
        $("input[name='mqIdAndOther']").val(arr.join(","));
    }else {
        for(var i = 0; i < channel.length; i++){
            var getRate = channel[i].speed;
            var id = channel[i].id || -1;
            if(!/^[0-9]+?$/.test(getRate)){
                layer.msg("拉取速度只能整数且不能为空",{icon:2});
                return;
            }
            arr[i] = channel[i].val + "|" + getRate  + "|" +id;
            total += Number(getRate);
        }
        $("input[name='mqIdAndOther']").val(arr.join(","));
    }

	var options = {
		beforeSubmit : function() {
			$(btn).attr("disabled", true);
		},
		success : function(data) {
			//
			
			if(data.result==null){
				$("#msg").text("服务器错误，请联系管理员").show();
				return;
			}
            if(data.result=="fail"){
                $("#msg").text(data.msg).show();
                return;
            }
			/*$("input[name='id']").val(data.id);
			$("#msg").text(data.msg).show();*/
            layer.msg(data.msg, {icon: 1,time: 1500},function(){
                parent.window.location.reload();
                closePage();
            });
          //  $(btn).attr("disabled", false);
		},
		url : "${ctx}/componentConf5point17point11/mqRelation/create",
		type : "post",
		timeout:30000
	};
	$("#mainForm").ajaxSubmit(options);
};
</script>
</body>
</html>